package org.smallreunion.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slim3.memcache.Memcache;
import org.smallreunion.model.BBSPost;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;

/**
 * FeedService
 *
 * RSSFeedを配信するService
 *
 * @author Sinmetal
 *
 */
public class FeedService {

    private BBSService bbsService = new BBSService();

    /**
     * BBS RSS Feedを取得
     *
     * @return
     * @throws IOException
     * @throws FeedException
     */
    public SyndFeed getFeed() {
        final String METHOD_NAME = "getFeed";
        String memcacheKey = this.getClass().getCanonicalName() + METHOD_NAME;
        if (Memcache.contains(memcacheKey)) {
            return Memcache.get(memcacheKey);
        }
        SyndFeed feed = createFeed();
        Memcache.put(memcacheKey, feed);
        return feed;
    }

    /**
     * BBS RSS Feedを生成
     *
     * @return
     * @throws IOException
     * @throws FeedException
     */
    protected SyndFeed createFeed() {
        SyndFeed feed = new SyndFeedImpl();
        feed.setTitle("小さな団欒場");
        feed.setLink("http://smallreunion.appspot.com/bbs/");
        feed.setDescription("これは小さな団欒場掲示板のRSSです。");

        List<SyndEntry> entries = new ArrayList<SyndEntry>();
        List<BBSPost> bbsPosts = bbsService.getBBSPostList();

        for (BBSPost bbsPost : bbsPosts) {
            entries.add(buildeEntry(bbsPost));
        }

        feed.setEntries(entries);

        return feed;
    }

    /**
     * BBSPostからSyndEntryを作成
     *
     * @param bbsPost
     * @return
     */
    protected SyndEntry buildeEntry(BBSPost bbsPost) {
        SyndEntry entry = new SyndEntryImpl();
        String title =
            String.format(
                "%s(%s)さんの書き込み",
                bbsPost.getTwitterScreenName(),
                bbsPost.getTwitterName());
        entry.setTitle(title);
        entry.setLink("http://smallreunion.appspot.com/bbs/");
        entry.setPublishedDate(bbsPost.getEntryDate());

        SyndContent description = new SyndContentImpl();
        description.setType("text/plain");
        description.setValue(bbsPost.getContent());

        entry.setDescription(description);
        return entry;
    }
}
